package com.prawn.search.service;

import com.prawn.search.dao.EducationInformationDao;
import com.prawn.search.pojo.EducationInformation;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;

import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

@Service
public class EducationInformationService {
    @Autowired
    private EducationInformationDao educationInformationDao;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 按时间排序倒序搜索
     * @param status
     * @param module
     * @param key
     * @param page
     * @param size
     * @return
     */
    public Page<EducationInformation> findByKey(int status,int module, String key, int page, int size) {
        Pageable pageable = PageRequest.of(page-1, size);

        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.boolQuery()
                        .must(QueryBuilders.termQuery("state",status))
                        .must(QueryBuilders.termQuery("module",module))
                        .must(QueryBuilders.multiMatchQuery(key,"title","brief","createBy")))
                .withPageable(pageable).withSort(SortBuilders.fieldSort("createDate").order(SortOrder.DESC))
                .build();

        return elasticsearchTemplate.queryForPage(searchQuery, EducationInformation.class);
    }

    /**
     * 按点击量排序倒序搜索
     * @param status
     * @param module
     * @param key
     * @param page
     * @param size
     * @return
     */
    public Page<EducationInformation> clickNumQuery(int status,int module, String key, int page, int size) {
        Pageable pageable = PageRequest.of(page-1, size);

        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.boolQuery()
                        .must(QueryBuilders.termQuery("state",status))
                        .must(QueryBuilders.termQuery("module",module))
                        .must(QueryBuilders.multiMatchQuery(key,"title","brief","createBy")))
                .withPageable(pageable).withSort(SortBuilders.fieldSort("clickNum").order(SortOrder.DESC))
                .build();

        return elasticsearchTemplate.queryForPage(searchQuery, EducationInformation.class);
    }
}
